package com.dianwoba.core.solr.where;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.dianwoba.core.solr.SolrConditionType;

/**
 * 简单where
 * @author 堵成杰
 * @since 2.0
 */
public class SolrSimpleWhere extends AbstractSolrWhere<SolrSimpleWhere>{
	
	/**
	 * 设定查询条件
	 */
	public void addCondition(
	    final SolrConditionType solrConditionType,
	    final String propertyName,
	    final Object value) {
		if (value == null){
			return;
		}
		if(value instanceof String && StringUtils.isEmpty(((String)value).trim())){
			return;
		}
		if(!containsNot){
			containsNot = solrConditionType.isNotCondition();
		}
		boolean matched = false;
		String regex = null;
		String field = SolrConditionType.FIELD_REPLACE_WORD_FRONT + propertyName + SolrConditionType.FIELD_REPLACE_WORD_BACK;
		if(solrConditionType == SolrConditionType.LE){
			regex = field + ":\\[([^\\s\\*]+) TO \\*\\]";
		}
		else if(solrConditionType == SolrConditionType.GE){
			regex = field + ":\\[\\* TO ([^\\s\\*]+)\\]";
		}
		else if(solrConditionType == SolrConditionType.LT){
			regex = field + ":\\{([^\\s\\*]+) TO \\*\\}";
		}
		else if(solrConditionType == SolrConditionType.GT){
			regex = field + ":\\{\\* TO ([^\\s\\*]+)\\}";
		}
		if(regex != null){
			Pattern p = Pattern.compile(regex);
			for(int i = 0; i < criteriaList.size(); i++){
				String q = criteriaList.get(i);
				Matcher m = p.matcher(q);
				if(m.find() && m.groupCount() == 1){
					String thisValue = solrConditionType.getConditionValue(value);
					String pairValue = m.group(1);
					if(solrConditionType == SolrConditionType.LE){
						q = field + ":[" + pairValue + " TO " + thisValue + "]";
					} else if(solrConditionType == SolrConditionType.GE){
						q = field + ":[" + thisValue + " TO " + pairValue + "]";
					} else if(solrConditionType == SolrConditionType.LT){
						q = field + ":{" + pairValue + " TO " + thisValue + "}";
					} else if(solrConditionType == SolrConditionType.GT){
						q = field + ":{" + thisValue + " TO " + pairValue + "}";
					}
					criteriaList.set(i, q);
					matched = true;
					break;
				}
			}
		}
		if(!matched){
			criteriaList.add(solrConditionType.getCondition(propertyName, value));
		}
	}

	public String getCriteria() {
		String criteria = StringUtils.join(criteriaList.toArray(), " AND ");
		return criteria;
	}

	public boolean containsNot(){
		return containsNot;
	}

}
